package com.valdemar.android.givemeanswers.common;

import java.util.HashMap;

import com.valdemar.android.givemeanswers.DeviceRegistrar;
import com.valdemar.android.givemeanswers.R;
import com.valdemar.android.givemeanswers.Util;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class AnswersApplicationContext extends Application
{
	HashMap<String, String> tempStore = new HashMap<String, String>();

	public static final String LOG_TAG = "GiveMeAnswers";

	@Override
	public void onCreate()
	{
		super.onCreate();
	}

	public boolean isNetworkAvailable()
	{
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
		return activeNetworkInfo != null;
	}

	
	
	/**
	 * A {@link BroadcastReceiver} to receive the response from a register or
	 * unregister request, and to update the UI.
	 */
	private final BroadcastReceiver mUpdateUIReceiver = new BroadcastReceiver()
	{
		@Override
		public void onReceive(Context context, Intent intent)
		{
			String accountName = intent.getStringExtra(DeviceRegistrar.ACCOUNT_NAME_EXTRA);
			int status = intent.getIntExtra(DeviceRegistrar.STATUS_EXTRA,
					DeviceRegistrar.ERROR_STATUS);
			String message = null;
			String connectionStatus = Util.DISCONNECTED;
			if (status == DeviceRegistrar.REGISTERED_STATUS)
			{
				message = getResources().getString(R.string.registration_succeeded);
				connectionStatus = Util.CONNECTED;
			}
			else if (status == DeviceRegistrar.UNREGISTERED_STATUS)
			{
				message = getResources().getString(R.string.unregistration_succeeded);
			}
			else
			{
				message = getResources().getString(R.string.registration_error);
			}

			// Set connection status
			SharedPreferences prefs = Util.getSharedPreferences(getApplicationContext());
			prefs.edit().putString(Util.CONNECTION_STATUS, connectionStatus).commit();

			// Display a notification
			Util.generateNotification(getApplicationContext(), String.format(message, accountName));
		}
	};

	public void registerC2DMReceiver()
	{
		 registerReceiver(mUpdateUIReceiver, new IntentFilter(Util.UPDATE_UI_INTENT));
		
	}

}
